package com.ztr.suanfa.threedes;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
 
public class TripleDESExample {
    public static void main(String[] args) throws Exception {
        String plainText = "z123456879";
        String key = "ThisIsSecretKey1234567890"; // 密钥长度必须是24个字符
 
        byte[] encryptedBytes = encrypt(plainText, key);
        String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("Encrypted Text: " + encryptedText);
 
        String decryptedText = decrypt(encryptedBytes, key);
        System.out.println("Decrypted Text: " + decryptedText);
    }

    /**
     *
     * @param plainText
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encrypt(String plainText, String key) throws Exception {
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        DESedeKeySpec spec = new DESedeKeySpec(keyBytes);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        SecretKey secretKey = keyFactory.generateSecret(spec);
 
        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
 
        return cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
    }

    /**
     *
     * @param encryptedBytes
     * @param key
     * @return
     * @throws Exception
     */
    public static String decrypt(byte[] encryptedBytes, String key) throws Exception {
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        DESedeKeySpec spec = new DESedeKeySpec(keyBytes);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        SecretKey secretKey = keyFactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }
}